package com.yzt.zhuju.richtext;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.yzt.zhuju.file.FileManager;
import com.yzt.zhuju.richtext.entity.EmojiData;
import com.yzt.zhuju.richtext.entity.GiftBaseInfo;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;


/**
 * 可显示表情的TextView
 *
 * @author lxq_x
 */
@SuppressLint("AppCompatCustomView")
public class EmojiTextView extends TextView {

    public static final int HAND_DRAWABLE_LOAD = 0x0001;
    private ArrayList<EmojiData> expressionList;
    private final Context context;
    private int gameResult = -1;
    public static Map<String, WeakReference<BitmapDrawable>> mWeakCatchBitmap = new HashMap<>();
//	private MyWeakReferenceHandler mHandler = new MyWeakReferenceHandler(this);

//	private static class MyWeakReferenceHandler extends WeakRefrenceHandler<EmojiTextView> {
//
//		public MyWeakReferenceHandler(EmojiTextView ref) {
//			super(ref);
//		}
//
//		@Override
//		protected void handleMessage(EmojiTextView ref, Message msg) {
//			switch (msg.what) {
//				case HAND_DRAWABLE_LOAD:
//					ref.setText(ref.getText());
//					break;
//			}
//		}
//	}

    public EmojiTextView(Context context) {
        this(context, null);
    }

    public EmojiTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EmojiTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        loadData();
    }

    private void loadData() {
//		List<EmojiFatherBean> mDatas = CacheEmojiManager.getInstance().getEmojiList();
//		expressionList = new ArrayList<>();
//		for(int index = 0;index < mDatas.size();index++){
//			expressionList.addAll(mDatas.get(0).getExpressionList());
//		}
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(createEmojiString(text), type);
    }

    private String mIconUrl;


    public void setIconUrl(String icon) {
        this.mIconUrl = icon;
    }

    /**
     * 创建表情字符串
     *
     * @param
     */
    private SpannableStringBuilder createEmojiString(CharSequence text) {
        if (text == null || TextUtils.isEmpty(text)) {
            return new SpannableStringBuilder("");
        }

        SpannableStringBuilder builder = new SpannableStringBuilder(text);
//		//礼物 表情
//		Pattern p = Pattern.compile("\\[\\w+\\]");
//		Matcher m = p.matcher(builder.toString());
//		while (m.find()) {
//			String faceKey = m.group();
//			if (faceKey != null) {
//				if (faceKey.equals("[女性]")) {
//					Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.icon_chatroom_woman);
//					if (drawable != null) {
//						setDrawableSpan(builder, m, drawable);
//						continue;
//					}
//				} else if (faceKey.equals("[男性]")) {
//					Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.icon_chatroom_man);
//					if (drawable != null) {
//						setDrawableSpan(builder, m, drawable);
//						continue;
//					}
//				} else if (faceKey.equals("[xys_vip]")) {
//
//				} else if (faceKey.equals("[xys_svip]")) {
//
//				} else if (faceKey.equals("[电话]")) {
//					Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.icon_chat_phone_hang_up);
//					if (drawable != null) {
//						setDrawableSpan(builder, m, drawable);
//						continue;
//					}
//				}
//				if (faceKey.equals("[视频]")) {
//					Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.icon_chat_video_hang_up);
//					if (drawable != null) {
//						setDrawableSpan(builder, m, drawable);
//						continue;
//					}
//				}
//
//				if (faceKey.equals("[文本]")) {
//					Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.icon_chat_emoji_text);
//					if (drawable != null) {
//						setDrawableSpan(builder, m, drawable);
//						continue;
//					}
//				}
//
//				if (faceKey.startsWith("[游戏")) {
//					Drawable localDrawable = getLocalGameResultDrawable(faceKey);
//					if (null != localDrawable) {
//						setDrawableSpan(builder, m, localDrawable);
//						continue;
//					} else {
//						localDrawable = getEmojiDrawable(faceKey);
//						if (localDrawable != null) {
//							setDrawableSpan(builder, m, localDrawable);
//							continue;
//						}
//					}
//				}
//
//				Drawable giftDrawable = getGiftDrawable(faceKey);
//				if (giftDrawable != null) {
//					setDrawableSpan(builder, m, giftDrawable);
//				}else {
//					if(!TextUtils.isEmpty(mIconUrl)){
//						Drawable iconDrawable = getIconDrawable();
//						if (iconDrawable != null) {
//							setDrawableSpan(builder, m, iconDrawable);
//							continue;
//						}
//					}
//
//				}
//
//				Drawable emojiDrawable = getEmojiDrawable(faceKey);
//				if (emojiDrawable != null) {
//					setDrawableSpan(builder, m, emojiDrawable);
//					continue;
//				}
//			}
//		}
        return builder;
    }

    private void setDrawableSpan(SpannableStringBuilder builder, Matcher m, Drawable drawable) {
//		VerticalImageSpan span = new VerticalImageSpan(drawable);
//		if (TextSpanUtils.isCanSetSpan(m.start(), m.end())) {
//			builder.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//		}
    }

    private Drawable getLocalGameResultDrawable(String faceKey) {
        Drawable drawable = null;
        try {
//			if (faceKey.length() > 1) {
//				int gameResultEmojiIconId = EmojiUtil.getGameResultEmojiIconId(faceKey, gameResult);
//				drawable = ContextCompat.getDrawable(getContext(), gameResultEmojiIconId);
//			}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return drawable;
    }

    public static List<Emoji> mEmojis = new ArrayList<>();

    public static class Emoji {
        public String icon;
        public String emoji;

        public Emoji(String icon, String emoji) {
            this.icon = icon;
            this.emoji = emoji;
        }
    }


    private Drawable getEmojiDrawable(String faceKey) {
        if (expressionList == null || expressionList.size() == 0) {
            return null;
        }
        for (EmojiData mEmojiData : expressionList) {
            if (faceKey.equals(mEmojiData.getName())) {
                String path = FileManager.getSingleEmoijPath() + File.separator + mEmojiData.getFileName();
                File mFile = new File(path);
                if (mFile.exists()) {
                    return new BitmapDrawable(getResources(), BitmapFactory.decodeFile(mFile.getPath()));
                } else {
                    getLoadHttp();
                }
            }
        }
        return null;
    }

    public void getLoadHttp() {

    }

    public static List<GiftBaseInfo> mGifts = new ArrayList<>();

    private Drawable getGiftDrawable(String faceKey) {
        if (mGifts == null || mGifts.isEmpty()) {
            mGifts = CacheEmojiManager.getInstance().getGiftList();
        }
        if (mGifts == null || mGifts.isEmpty()) {
            return null;
        }
        for (GiftBaseInfo giftData : mGifts) {
            if (faceKey.contains(giftData.giftName)) {
                final String giftIcon = giftData.icon;
                if (mWeakCatchBitmap.get(giftIcon) != null) {
                    return mWeakCatchBitmap.get(giftIcon).get();
                } else {
                    RequestOptions options = new RequestOptions()
                            .override(40, 40)
                            .circleCrop();
                    Glide.with(getContext())
                            .load(giftData.icon)
                            .apply(options).into(new SimpleTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            BitmapDrawable mBitmapDrawable = (BitmapDrawable) resource;
                            mWeakCatchBitmap.put(giftIcon, new WeakReference<>(mBitmapDrawable));
//							mHandler.sendEmptyMessage(HAND_DRAWABLE_LOAD);
                        }
                    });
                }
            }
        }
        return null;
    }


    public Drawable getIconDrawable() {
//		File file = FrescoUtils.getFileFromDiskCache(mIconUrl);
//		if (file != null) {
//			return new BitmapDrawable(getResources(),BitmapFactory.decodeFile(file.getPath()));
//		} else if (mWeakCatchBitmap.get(mIconUrl) != null) {
//			return mWeakCatchBitmap.get(mIconUrl).get();
//		} else {
//			FrescoUtils.getBitmapByUrl(mIconUrl, context, 0, 0, new FrescoUtils.BitmapListener() {
//				@Override
//				public void onSuccess(Bitmap bitmap) {
//					mWeakCatchBitmap.put(mIconUrl, new WeakReference<>(new BitmapDrawable(getResources(), bitmap)));
//					mHandler.sendEmptyMessage(HAND_DRAWABLE_LOAD);
//				}
//
//				@Override
//				public void onFail() {
//
//				}
//			});
//		}
        /**
         * IreneBond need
         */
        return null;
    }

    public void setGameResult(int gameResult) {
        this.gameResult = gameResult;
    }
}
